<?php

namespace App\Transformers;

use App\Models\Node;
use League\Fractal\TransformerAbstract;

class NodeTransformer extends TransformerAbstract
{
    /**
     * @var array
     */
    protected $availableIncludes = ['articles', 'parent', 'children'];

    /**
     * @param Node $node
     * @return array
     */
    public function transform(Node $node)
    {
        return $node->attributesToArray();
    }

    /**
     * @param Node $node
     * @return \League\Fractal\Resource\Collection|\League\Fractal\Resource\NullResource
     */
    public function includeArticles(Node $node)
    {
        if (!$node->articles) {
            return $this->null();
        }

        return $this->collection($node->articles, new ArticleTransformer());
    }

    /**
     * @param Node $node
     * @return \League\Fractal\Resource\Collection|\League\Fractal\Resource\NullResource
     */
    public function includeChildren(Node $node)
    {
        if (!$node->children) {
            return $this->null();
        }

        return $this->collection($node->children, new NodeTransformer());
    }

    /**
     * @param Node $node
     * @return \League\Fractal\Resource\Collection|\League\Fractal\Resource\NullResource
     */
    public function includeParent(Node $node)
    {
        if (!$node->parent) {
            return $this->null();
        }

        return $this->collection($node->parent, new NodeTransformer());
    }
}
